package com.haiheng.voiceandbook.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;


import com.haiheng.voiceandbook.Constants;
import com.haiheng.voiceandbook.MainActivity;
import com.haiheng.voiceandbook.MyApplication;
import com.xmlywind.sdk.common.models.sigdsp.pb.DeviceId;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * app工具类
 *
 * @author songjiali
 * @version 1.0.0
 * @filename AppUtils.java
 * @time 2018/10/22 17:25
 * @copyright(C) 2018 深圳市海恒智能科技有限公司
 */
public class AppUtils {
    public static String getUniqueId(Context context){
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        try {
            return toMD5(id);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return id;
        }
    }


    private static String toMD5(String text) throws NoSuchAlgorithmException {
        //获取摘要器 MessageDigest
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        //通过摘要器对字符串的二进制字节数组进行hash计算
        byte[] digest = messageDigest.digest(text.getBytes());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            //循环每个字符 将计算结果转化为正整数;
            int digestInt = digest[i] & 0xff;
            //将10进制转化为较短的16进制
            String hexString = Integer.toHexString(digestInt);
            //转化结果如果是个位数会省略0,因此判断并补0
            if (hexString.length() < 2) {
                sb.append(0);
            }
            //将循环结果添加到缓冲区
            sb.append(hexString);
        }
        //返回整个结果
        return sb.toString();
    }


    /**
     * 获取Ethernet的MAC地址
     * @return
     */
    public static String getMacAddress() {
        try {
            return loadFileAsString("/sys/class/net/eth0/address").toUpperCase(Locale.ENGLISH).substring(0, 17);
        } catch (IOException e) {
            return null;
        }
    }

    private static String loadFileAsString(String filePath) throws java.io.IOException{
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024]; int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

//    /**
//     * 获取Ethernet的MAC地址
//     * @return
//     */
//    private String getMacAddress1() {
//
//        EthernetManager ethManager = (EthernetManager) MainActivity.this.getSystemService("ethernet");
//        return ethManager.getMacAddr()==null?"":ethManager.getMacAddr();
//    }
    /**
     * 判断网络是否连接,不能检查网络连通性
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    /**
     * 判断网路不连接,不能检查网络连通性
     *
     * @param context
     * @return
     */
    public static boolean isNotConnected(Context context) {
        return !isConnected(context);
    }

    /**
     * 0代表连接的是WiFi，1代表连接的是GPRS,2 代表无网络
     *
     * @return
     */
    public static int getNetworkAvailableType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return 2;
        }
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        if (networkinfo == null || !networkinfo.isAvailable()) {
            return 2;
        } else {
            boolean wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
            if (wifi) {
                return 0;
            } else {
                return 1;
            }
        }
    }

    /**
     * 判断应用是否在运行
     *
     * @param context
     * @return
     */
    public static boolean isAppRunning(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        for (RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(context.getPackageName())
                    || info.baseActivity.getPackageName().equals(context.getPackageName())) {
                isAppRunning = true;
                break;
            }
        }
        return isAppRunning;
    }

    /**
     * 判断服务是否运行
     *
     * @param context   上下文
     * @param className 服务类名
     * @return
     */
    public static boolean isServiceRunning(Context context, String className) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> info = activityManager.getRunningServices(100);
        if (info == null || info.size() == 0) return false;
        for (ActivityManager.RunningServiceInfo aInfo : info) {
            if (className.equals(aInfo.service.getClassName())) return true;
        }
        return false;
    }

    /**
     * 验证对象属性是否为空
     *
     * @param obj          待验证对象
     * @param excludeField 要排除验证的对象属性
     * @return
     * @throws IllegalAccessException
     */
    public static boolean checkObjFieldIsNull(Object obj, String[] excludeField) throws IllegalAccessException {
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field f : declaredFields) {
            f.setAccessible(true);
            String name = f.getName();
            for (int i = 0; i < excludeField.length; i++) {
                if (!name.equals(excludeField[i])) {
                    Object object = f.get(obj);
                    if (object == null || (object != null && "".equals(object.toString().trim()))) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 判断某activity是否处于栈顶
     *
     * @param cls
     * @param context
     * @return
     */
    public static boolean isActivityTop(Class cls, Context context) {
        Class<?> topActivity = getTopActivity(context);
        return topActivity.getName().equals(cls.getName());
    }

    /**
     * 获取栈顶Activity
     *
     * @param context
     * @return
     */
    public static Class<?> getTopActivity(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        try {
            String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
            return Class.forName(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 字符串非空判断
     *
     * @param str true为空
     * @return
     */
    public static boolean isEmpty(String str) {
        if (TextUtils.isEmpty(str)) {
            return true;
        } else if (str.trim().length() == 0) {
            return true;
        } else if (str.equals("null")) {
            return true;
        }
        return false;
    }

    /**
     * 集合非空判断
     *
     * @param collection true为空
     * @return
     */
    public static boolean isEmpty(Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }

    /**
     * 比较当前url知否在指定页面中
     *
     * @param currentUrl   当前页面
     * @param comparePages 需要比较的页面数组
     * @return
     */
    public static boolean compareHtmlPage(String currentUrl, String[] comparePages) {
        if (comparePages == null || comparePages.length == 0) {
            return false;
        }
        for (String pageUrl : comparePages) {
            if (currentUrl.contains(pageUrl)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 获取url 指定name的value
     *
     * @param url  请求路径
     * @param name 名字
     * @return
     */
    public static String getUrlValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }


    /**
     * 删除ArrayList中重复元素，保持顺序
     *
     * @param list
     */
    public static List removeDuplicateWithOrder(List list) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        list.clear();
        list.addAll(newList);
        return list;
    }

    /**
     * 读取assets文件的内容
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getFileContentFromAssets(Context context, String fileName) {
        String result = "";
        try {
            InputStream is = context.getAssets().open(fileName);
            int count = is.available();
            byte[] buffer = new byte[count];
            is.read(buffer);
            is.close();
            result = new String(buffer, "utf8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 对比两个list，返回list差集（新数据-老数据）
     *
     * @param oldData 老数据
     * @param newList 新数据
     * @return
     */
    public static List<String> mapCompare(List<String> oldData, List<String> newList) {
        if (oldData != null && !oldData.isEmpty()) {
            Map<String, String> dataMap = new HashMap<String, String>();
            for (String id : oldData) {
                dataMap.put(id, id);
            }

            List<String> temp = new ArrayList<String>();
            for (String id : newList) {
                if (!dataMap.containsKey(id)) {
                    temp.add(id);
                }
            }
            return temp;
        } else {
            return newList;
        }
    }

    /**
     * 从tags集合中随机取n个数
     *
     * @param tags
     * @param n
     * @return
     */
    public static List<String> getRandomArray(List<String> tags, int n) {
        List<String> list = new ArrayList<String>();
        Random random = new Random();
        int size = tags.size();
        if (tags == null || n > size) {
            return list;
        }
        Set<String> temp = new HashSet<>();
        for (int i = 0; i < size; i++) {
            // 去一个随机数，随机范围是list的长度
            int index = random.nextInt(size);
            String s = tags.get(index);
            temp.add(s);
            if (temp.size() == n) {
                break;
            }
        }
        List<String> result = new ArrayList<>(temp);
        return result;
    }



    public static String getDeviceId() {
        String hardwareInfo = android.os.Build.BOARD + android.os.Build.BRAND + android.os.Build.DEVICE + android.os.Build.DISPLAY
                + android.os.Build.HOST + android.os.Build.ID + android.os.Build.MANUFACTURER + android.os.Build.MODEL
                + android.os.Build.PRODUCT + android.os.Build.TAGS + android.os.Build.TYPE + android.os.Build.USER
                +SpUtil.INSTANCE.getString(MyApplication.Companion.getInstance(), Constants.DEVICEID,"");
        String deviceId = MD5Util.encryptMD5ToString(hardwareInfo);
        return deviceId;
    }

    /**
     * 请求ROOT权限后执行命令（最好开启一个线程）
     * @param cmd	(pm install -r *.apk)
     * @return
     */
    public static boolean runRootCommand(String cmd) {
        Process process = null;
        DataOutputStream os = null;
        BufferedReader br = null;
        StringBuilder sb = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd+"\n");
            os.writeBytes("exit\n");
            br = new BufferedReader(new InputStreamReader(process.getInputStream()));

            sb = new StringBuilder();
            String temp=null;
            while((temp = br.readLine())!=null){
                sb.append(temp+"\n");
                if("Success".equalsIgnoreCase(temp)){
                    Log.e("runRootCommand","----------"+sb.toString());
                    return true;
                }
            }
            process.waitFor();
        } catch (Exception e) {
            Log.e("runRootCommand","异常----------"+sb.toString());
        }
        finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
                if(br!=null){
                    br.close();
                }
                process.destroy();
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }
}
